// pages/goods_detail/index.js
import { request } from "../../request/index.js";
import regeneratorRuntime from "../../lib/runtime/runtime";

Page({

  data: {
    goodsObj: {},
    isCollect: false
  },
  // 商品对象
  GoodsInfo: {},  

  onShow: function () {
    let pages =  getCurrentPages()
    let options = pages[pages.length-1].options
    this.getGoodsDetail(options.goods_id)
    
  },

  async getGoodsDetail(goods_id) {
    const goodsObj = await request({url: '/goods/detail', data: {goods_id}})
    this.GoodsInfo = goodsObj
    // 商品收藏
    let collect = wx.getStorageSync('collect')||[]
    let isCollect = collect.some(v => v.goods_id===this.GoodsInfo.goods_id)
    this.setData({
      goodsObj: {
        goods_name: goodsObj.goods_name,
        goods_price: goodsObj.goods_price,
        // iphone部分手机不识别webp格式图片=>jpg
        goods_introduce: goodsObj.goods_introduce.replace(/\.webp/g, '.jpg'),
        pics: goodsObj.pics
      },
      isCollect
    })
  },
  // 轮播图放大预览
  handlePreviewImage(e) {
    const urls = this.GoodsInfo.pics.map(v => v.pics_mid)
    const current = e.currentTarget.dataset.url
    wx.previewImage({
      current,
      urls
    })
   
  },
  // 加入购物车
  handleCartAdd() {
    let cart = wx.getStorageSync('cart')||[]
    let index = cart.findIndex(v => v.goods_id===this.GoodsInfo.goods_id)
    if(index===-1) {
      this.GoodsInfo.num = 1
      this.GoodsInfo.checked = true
      cart.push(this.GoodsInfo)
    }else {
      cart[index].num++
    }
    wx.setStorageSync('cart', cart)
    wx.showToast({
      title: '加入成功',
      icon: 'success',
      duration: 1000,
      // 1秒后用户才能点击按钮
      mask: true
    })
      
  },
  // 商品收藏
  handleCollect() {
    let isCollect = false
    let collect = wx.getStorageSync('collect')||[]
    let index = collect.findIndex(v => v.goods_id===this.GoodsInfo.goods_id)
    if(index !== -1) {
      // 商品已经收藏
      collect.splice(index, 1)
      isCollect = false
      wx.showToast({
        title: '取消成功',
        icon: 'success',
        duration: 1000
      })
    }else {
      // 未收藏
      collect.push(this.GoodsInfo)
      isCollect = true
      wx.showToast({
        title: '收藏成功',
        icon: 'success',
        duration: 1000
      })
    }
    wx.setStorageSync('collect', collect)
    this.setData({ isCollect })
    
  }
})